package cn.wzx.controller;

import cn.wzx.entity.Blogger;
import cn.wzx.entity.Boke;
import cn.wzx.entity.User;
import cn.wzx.service.BlogService;
import cn.wzx.util.RespJson;
import cn.wzx.util.SessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.Map;

@Controller
@RequestMapping("/client")
public class BloggerController {
    @Autowired
    BlogService blogService;

    @RequestMapping("/blog")
    public String blog(){
        return "client/blogger";
    }

    @ResponseBody
    @RequestMapping("/addBlog")
    public Blogger addBlog(@RequestBody Map<String,Object> map){
        Boke boke = new Boke();
        Blogger blogger = new Blogger();
        boke.setUid(SessionUtils.getUid());
        boke.setBody((String) map.get("body"));//正文
        blogger.setDigest((String)map.get("digest"));//摘要
        blogger.setTitle((String)map.get("title"));//标题
        blogger.setTypeId((String)map.get("typeId"));//类别
        blogger.setTpress(new Date());//发布时间
        blogger.setAuthor(SessionUtils.getUsername());//发表作者
        blogger.setPageviews(0);//阅读量
        blogger.setLikenum(0);
        StringBuilder sb = new StringBuilder();
        sb.append("摘要:本文由");
        sb.append(blogger.getAuthor());
        sb.append("分享,原题\"");
        sb.append(blogger.getTitle()+"\""+"。");
        //摘要是文章的前30个字
        String digest = blogger.getDigest();
        if(digest.length()>=30){
            sb.append(digest.substring(0,30));
        }else{
            sb.append(digest);
        }
        sb.append("...");
        blogger.setDigest(sb.toString());
        blogService.add(boke,blogger);
        return blogger;
    }

    @ResponseBody
    @RequestMapping("/findBlogsByUid")
    public Map<String ,Object> findBlogsByUid(){
        return RespJson.pack(200,"",blogService.fingBlogsByUid());
    }

    @ResponseBody
    @RequestMapping("/del/{blogid}/{typeid}")
    public Map<String,Object> del(@PathVariable("blogid") String blogId,@PathVariable("typeid") String typeId){
        blogService.del(blogId, typeId);
        return RespJson.pack(200,"删除成功",null);
    }

    @ResponseBody
    @RequestMapping("/addLike/{blogid}")
    public Map<String,Object> addLike(@PathVariable("blogid")String blogid){
        System.out.println("blogid==="+blogid);
        User user = SessionUtils.getUser();
        int n = blogService.addLike(blogid, user.getId());
        return n==1?RespJson.pack(200,"点赞成功",null):RespJson.pack(200,"取消点赞",null);
    }
}
